package com.njuse_czf.kg.web.service.impl.handler;

import com.njuse_czf.kg.web.request.GraphQuery;
import com.njuse_czf.kg.web.service.KGGraphService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


public class OfferHandler extends AbstractQuestionHandler{
    @Override
    public void handleQuestion(QuestionCtx questionCtx, String question, KGGraphService kgGraphService) {

        //regix规则进行匹配
        String regix1 = "[wW]hat(?:'s|\\s+is)\\s* + the\\s* + positive\\s* + effect\\s* + of\\s* + ([^?]+)\\s*\\??";

        ArrayList<String> regix = new ArrayList<>();
        regix.add(regix1);

        for (String r : regix) {
            Pattern pattern = Pattern.compile(r, Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(question);

            if (matcher.find()) {
                //提取匹配到的名
                String name = matcher.group(1);
                List<String> nodes = getAllObject(name);
                //构造Query
                for (String nodeName : nodes) {
                    GraphQuery query = new GraphQuery();
                    query.setDomain(questionCtx.getDomain());
                    query.setMatchType(1);
                    query.setNodeName(nodeName);
                    query.setRelation(new String[]{"positive effect"});

                    List<HashMap> res = (List<HashMap>) kgGraphService.queryGraphResult(query).get("node");

                    //提取出实体的优点
                    List<String> nodeNames = res.stream()
                            .map(map -> (String) map.get("name"))
                            .collect(Collectors.toList());

                    String currentAnswer = nodeNames.stream()
                            .map(s -> s.endsWith(".") ? s.substring(0, s.length() - 1) : s)
                            .collect(Collectors.joining(","));

                    if (!currentAnswer.isEmpty()) {
                        currentAnswer = nodeName + "offers" + currentAnswer + ".";

                        questionCtx.addAnswer(currentAnswer);

                        //删除已经匹配的部分
                        question = matcher.replaceFirst("");
                    }
                }
                break;
            }
        }
        this.getNextHandler().handleQuestion(questionCtx, question, kgGraphService);
    }
}
